Page({
  data: {
    currentFilter: 'all',
    activities: [] as any[],
    filteredActivities: [] as any[],
    loading: false
  },

  onLoad() {
    // 初始化获取活动列表
    this.getActivityList()
  },

  onShow() {
    // 页面显示时刷新活动列表
    this.getActivityList()
  },

  // 获取活动列表
  async getActivityList() {
    this.setData({ loading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'activityManager',
        data: {
          action: 'getList',
          status: this.data.currentFilter === 'all' ? undefined : this.data.currentFilter
        }
      })

      const response = result.result as any
      if (response && response.success) {
        const activities = response.data.activities || []
        this.setData({
          activities: activities
        })
        
        // 重新过滤活动列表
        this.filterActivities()
        
        console.log('获取活动列表成功:', activities.length, '个活动')
      } else {
        console.error('获取活动列表失败:', response?.message)
        wx.showToast({
          title: response?.message || '获取活动列表失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('获取活动列表失败:', error)
      wx.showToast({
        title: '获取活动列表失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 切换过滤器
  switchFilter(e: any) {
    const filter = e.currentTarget.dataset.filter
    this.setData({
      currentFilter: filter
    })
    
    this.filterActivities()
  },

  // 过滤活动列表
  filterActivities() {
    const { activities, currentFilter } = this.data
    
    let filteredActivities = []
    
    switch (currentFilter) {
      case 'ongoing':
        filteredActivities = activities.filter(item => item.statusText === '进行中')
        break
      case 'ended':
        filteredActivities = activities.filter(item => item.statusText === '已结束')
        break
      case 'draft':
        filteredActivities = activities.filter(item => item.statusText === '草稿')
        break
      default:
        filteredActivities = activities
    }
    
    this.setData({
      filteredActivities
    })
  },

  // 去创建活动页面
  goToCreateActivity() {
    wx.navigateTo({
      url: '/pages/admin/create/index'
    })
  },

  // 去用户管理页面
  goToUserManager() {
    wx.navigateTo({
      url: '/pages/admin/userManager/index'
    })
  },

  // 编辑活动
  editActivity(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/create/index?id=${id}`
    })
  },

  // 查看活动数据
  viewActivityData(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/data/index?id=${id}`
    })
  },

  // 管理活动
  manageActivity(e: any) {
    const id = e.currentTarget.dataset.id
    const activity = this.data.activities.find(item => item._id === id)
    
    if (!activity) {
      wx.showToast({
        title: '活动不存在',
        icon: 'none'
      })
      return
    }

    // 根据活动状态显示不同的操作选项
    const actions: string[] = []
    
    if (activity.status === 'draft') {
      actions.push('发布活动', '删除活动')
    } else if (activity.status === 'ongoing') {
      actions.push('暂停活动', '结束活动')
    } else if (activity.status === 'paused') {
      actions.push('恢复活动', '结束活动')
    }
    
    actions.push('查看详情', '取消')
    
    wx.showActionSheet({
      itemList: actions,
      success: (res) => {
        const action = actions[res.tapIndex]
        this.handleActivityAction(id, action, activity)
      }
    })
  },

  // 处理活动操作
  async handleActivityAction(activityId: string, action: string, activity: any) {
    switch (action) {
      case '发布活动':
        await this.toggleActivityStatus(activityId, 'ongoing')
        break
      case '暂停活动':
        await this.toggleActivityStatus(activityId, 'paused')
        break
      case '恢复活动':
        await this.toggleActivityStatus(activityId, 'ongoing')
        break
      case '结束活动':
        await this.toggleActivityStatus(activityId, 'ended')
        break
      case '删除活动':
        await this.deleteActivity(activityId)
        break
      case '查看详情':
        wx.navigateTo({
          url: `/pages/activity/detail/index?id=${activityId}&admin=true`
        })
        break
    }
  },

  // 切换活动状态
  async toggleActivityStatus(activityId: string, status: string) {
    wx.showLoading({
      title: '操作中...'
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'activityManager',
        data: {
          action: 'toggleStatus',
          activityId: activityId,
          status: status
        }
      })

      const response = result.result as any
      if (response && response.success) {
        wx.showToast({
          title: '操作成功',
          icon: 'success'
        })
        
        // 刷新活动列表
        this.getActivityList()
      } else {
        wx.showToast({
          title: response?.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('切换活动状态失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 删除活动
  async deleteActivity(activityId: string) {
    // 确认删除
    const confirmResult = await new Promise<boolean>((resolve) => {
      wx.showModal({
        title: '确认删除',
        content: '删除后无法恢复，确定要删除这个活动吗？',
        success: (res) => {
          resolve(res.confirm)
        },
        fail: () => {
          resolve(false)
        }
      })
    })
    
    if (!confirmResult) {
      return
    }
    
    wx.showLoading({
      title: '删除中...'
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'activityManager',
        data: {
          action: 'delete',
          activityId: activityId
        }
      })

      const response = result.result as any
      if (response && response.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 刷新活动列表
        this.getActivityList()
      } else {
        wx.showToast({
          title: response?.message || '删除失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('删除活动失败:', error)
      wx.showToast({
        title: '删除失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  }
}) 